<?php
/**
 * 商品规格逻辑层
 * @author maniac
 */
namespace app\common\logic;

use app\common\model\GoodSpecValue;

class GoodSpecs extends Base
{
    /**
     * 添加/编辑逻辑处理
     * @param  array $data 请求的信息
     */
    public function save($data)
    {
        foreach ($data['specs'] as $k => $v) {
            if (!trim($v)) {
                exception('属性名称必须填写');
            }
        }
        $result = parent::save($data);
        $update = [];
        $index  = 0;
        foreach ($data['specs'] as $k => $v) {
            $update[$index] = [
                'spec_value_name' => $v,
                'spec_value_data' => $data['show_type'] == 2 ? $data['color'][$k] : '',
                'list_order'      => $data['spec_value_order'][$k] ? (int)$data['spec_value_order'][$k] : 0,
            ];
            if (isset($data['spec_value_id'][$k]) && $data['spec_value_id'][$k]) {
                $update[$index]['id'] = $data['spec_value_id'][$k];
            } else {
                $update[$index]['spec_id'] = isset($data['id']) && $data['id'] ? $data['id'] : $result;
            }
            $index++;
        }
        // 批量添加
        if (!empty($update)) {
            (new GoodSpecValue)->saveAll($update);
        }
        return $result;
    }
}
